package net.jxvtc.eshop.web.servlet.client;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import net.jxvtc.eshop.domain.User;
import net.jxvtc.eshop.exception.RegisterException;
import net.jxvtc.eshop.service.UserService;
import net.jxvtc.eshop.utils.ActiveCodeUtils;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet{
   @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	doPost(req,resp);
}
   @Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		User user=new User();
		try {
			BeanUtils.populate(user, req.getParameterMap());
			user.setActiveCode(ActiveCodeUtils.createActiveCode());
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		UserService service=new UserService();
		try {
			service.register(user);
		} catch (RegisterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resp.getWriter().write(e.getMessage());
			return;
		}
		resp.sendRedirect(req.getContextPath()+"/client/registersuccess.jsp");
		
	}
}
